<?php

declare(strict_types=1);

namespace App\Third\Listener;

use App\Activity\Model\ActivityModel;
use App\Common\Constants\ErrorCode;
use App\Common\Constants\Stakeholder;
use App\Common\Exception\RefundException;
use App\Common\Service\BaseService;
use App\Order\Service\OrderGoodsService;
use App\Order\Service\OrderRefundService;
use App\Order\Service\OrderService;
use App\Order\Service\RefundGoodsService;
use App\Order\Task\UpdateFreeStatus;
use App\Third\Event\Refunded;
use Exception;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Psr\Container\ContainerInterface;

/**
 * @Listener
 */
class RefundedListener implements ListenerInterface
{
    /**
     * @var ContainerInterface
     */
    private $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function listen(): array
    {
        return [
            Refunded::class
        ];
    }

    public function process(object $event)
    {
        $orderInfo = $event->order;
        $type = $event->type;
        $container = $this->container;
        try {

            if ($type == 'user') {
                // order_goods => id => status=1 (1退款, 0不退款)
                foreach ($orderInfo['refundOrderGoodsInfo'] as $k => $v) {
                    $id = $v['id'];
                    unset($v['id']);
                    $container->get(OrderGoodsService::class)->update(['id' => $id], $v);
                }
//                $this->container->get(OrderGoodsService::class)->update(['id', 'in', $orderInfo['refundOrderGoodsInfo']], ['status' => 1,'refund_at' => date('Y-m-d H:i:s', time())]);
                // order_refund => order_no => status=2,handle_type=2,refund_at=date()
                $orderRefundUpdateData = ['status' => Stakeholder::REFUND_COMPLETE, 'handle_type' => Stakeholder::REFUND_PROCESSED, 'refund_at' => date('Y-m-d H:i:s', time())];
                $container->get(OrderRefundService::class)->update(['refund_no' => $orderInfo['refund_no']], $orderRefundUpdateData);
                // order_refund_goods => order_no => status=1
                $container->get(RefundGoodsService::class)->update(['refund_no' => $orderInfo['refund_no']], ['status' => 1]);
                // 更新订单状态 // order => order_no => is_whole? , refund_at=date(), status=5?
                $is_whole = $orderInfo['allOrPart'] == 'part' ? Stakeholder::PART_REFUND : Stakeholder::WHOLE_REFUND;
                $orderUpdateData = ['is_whole' => $is_whole, 'is_shop_refund' => 0, 'status' => Stakeholder::ORDER_REFUNDED, 'refund_at' => date('Y-m-d H:i:s', time())];

            }
            if ($type == 'shop') {
                // order_goods => id => status=1 (1退款, 0不退款)
                foreach ($orderInfo['updateOrderGoodsData'] as $k => $v) {
                    $id = $v['id'];
                    unset($v['id']);
                    $container->get(OrderGoodsService::class)->update(['id' => $id], $v);
                }
                // 更新订单状态 // order => order_no => is_whole? , refund_at=date(), status=5?
                $is_whole = $orderInfo['allOrPart'] == 'part' ? Stakeholder::PART_REFUND : Stakeholder::WHOLE_REFUND;
                $orderUpdateData = ['is_whole' => $is_whole, 'is_shop_refund' => 1, 'refund_at' => date('Y-m-d H:i:s', time())];
                if ($orderInfo['allOrPart'] == 'whole') {
                    $orderUpdateData['status'] = Stakeholder::ORDER_REFUNDED;
                }
            }

            if ($orderInfo['order_type'] == Stakeholder::ORDER_TYPE_FREE){
                if ($type == 'user'){
                    $free_info = $this->freeStatusCondition($orderInfo);
                    $orderUpdateData = array_merge($orderUpdateData, $free_info['free']);
                    $container->get(UpdateFreeStatus::class)->refundHandle($orderInfo, $free_info['act']);
                }
            }
            $container->get(OrderService::class)->update(['order_no' => $orderInfo['order_no']], $orderUpdateData);

        } catch (Exception $e) {
            $param = json_encode(['type' => $type, 'orderInfo' => $orderInfo, 'error' => $e->getMessage()]);
            $container->get(BaseService::class)->write('退款更新数据错误', $param);
            throw new RefundException('退款更新数据失败', ErrorCode::SYSTEM_INVALID);
        }
    }

    protected function freeStatusCondition($order){
        $act = ActivityModel::query()->where('activityID', $order['activity_id'])->first();
        return [
            'act' => $act,
            'free' => ['is_freed' => 3, 'free_step' => time() > strtotime($act->end_date) ? 5 : 3, 'free_success_time' => null]
        ];
    }

}
